<?php
/**
 *  func.php 公共函数库
 *
 * @copyright	(c) 2011 Movie All rights reserved.
 * @author		Feng <dcsite@qq.com> <QQ:729913515>
 * @lastmodify	2011-04-09 21:28:37
 */

function array_unique_fb($array2D){
     foreach ($array2D as $v){
         $v = join(",",$v);
         $temp[] = $v;
     }
     $temp = array_unique($temp);
    foreach ($temp as $k => $v){
        $temp[$k] = explode(",",$v);
    }
    return $temp;
}
  
function sysSortArray($ArrayData, $KeyName1, $SortOrder1 = "SORT_ASC", $SortType1 = "SORT_REGULAR") {
	if (!is_array($ArrayData)) {
		return $ArrayData;
	} 
	$ArgCount = func_num_args(); 
	for($I = 1;$I < $ArgCount;$I ++) {
		$Arg = func_get_arg($I);
		if (!eregi("SORT", $Arg)) {
			$KeyNameList[] = $Arg;
			$SortRule[] = '$' . $Arg;
		} else {
			$SortRule[] = $Arg;
		} 
	} 
	foreach($ArrayData AS $Key => $Info) {
		foreach($KeyNameList AS $KeyName) {
			${$KeyName}[$Key] = $Info[$KeyName];
		} 
	} 
	$EvalString = 'array_multisort(' . join(",", $SortRule) . ',$ArrayData);';
	eval ($EvalString);
	return $ArrayData;
} 
  
function arrayUnique($arr, $key) { 
	$tmp_arr = array(); 
	foreach($arr as $k => $v) { 
		if(in_array($v[$key], $tmp_arr)) { 
			unset($arr[$k]); 
		} else { 
			$tmp_arr[] = $v[$key]; 
		} 
	} 
	sort($arr); 
	return $arr; 
} 

function multi_array_sort($multi_array,$sort_field,$sort_type = SORT_ASC){
    if (!is_array($multi_array)) return FALSE;
    foreach ($multi_array as $row){
        if(! is_array($row)) return FALSE;
        $arr_field[] = $row[$sort_field];
    }
    array_multisort($arr_field,$sort_type,$multi_array);
    return $multi_array;
}



function checkLen($str, $minLen, $maxLen) {
	$strLen = @strlen($str);
	if(($strLen >= $minLen) && ($strLen <= $maxLen)) {
		return TRUE;
	} else {
		return FALSE;
	}
}

function csubstr($str,$length,$suffix=0){
	if(function_exists("mb_substr")){
		$slice = mb_substr($str,0,$length,'utf-8');
	}else{
		$re['utf-8']	= "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312']	= "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']		= "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		preg_match_all($re['utf-8'], $str, $match);
		$slice = join("", array_slice($match[0],0, $length));
	}
	if($suffix == '1') {
		if($slice == $str){
			return $slice;
		}else{
			return $slice."…";
		}
	}
	return $slice;
}

function cookieset($name,$value='',$cookiedate = 0) {
	global $timestamp;
    $date = $date == 0 ? $timestamp + 8640000 : $timestamp + $date;
    $name = 'movie_'.$name;
    setcookie($name,$value,$date,'/');
}

function cookieget($name) {
    if (isset($_COOKIE['movie_'.$name])) {
        return $_COOKIE['movie_'.$name];
    }
    return FALSE;
}


function daddslashes($string) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}


function de($var){
	$backtrace = debug_backtrace();	
	include CLASS_PATH.'/tpl/debug.php';	
}

function debuginfo() {
	global $starttime;
	$mtime = explode(' ', microtime());
	$debuginfo = '执行时间 '.number_format(($mtime[1] + $mtime[0] - $starttime), 8).' 秒，'.'内存使用 '.number_format(memory_get_usage()).' 字节，';
	return $debuginfo;
}

function fileExt($filename){
	return trim(substr(strrchr($filename, '.'), 1));
}

function fileWrite($file, $content=''){
	$dir = dirname($file);
	if(!is_dir($dir)){
		makeDir($dir);
	}
	if(function_exists('file_put_contents')){
		return @file_put_contents($file, $content);
	} else{
		$fp = @fopen($file, 'wb');
		if(!@fwrite($fp, $content)){
			return false;
		}
		fclose($fp);
	}
	return true;
}

function getDB(){	
	global $mysql;
	require_once(CLASS_PATH."class/mysql.class.php");
	$DB = new MySql ($mysql['dbhost'],$mysql['dbuser'],$mysql['dbpass'],$mysql['dbname']);
	return $DB;
}

function getIp() {	
	$onlineip = null;
	$onlineipmatches = array();
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	$onlineip = addslashes($onlineip);
	@preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
	$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
	unset($onlineipmatches);
	return $onlineip;
}

function getMember($value='') {
	if(!empty($_SESSION['uid'])){
		$user['uid'] = $_SESSION['uid'];
		$user['username'] = $_SESSION['username'];
		$user['logintip'] = $user['username'].'，您好！&nbsp;<a href="/accounts/">会员中心</a> | <a href="/accounts/logout/">退出</a>';
		if(!empty($value)){
			return $user[$value];
		}
		return $user;
	}
	return false;
}

function getRating($v){
	$s = $v['rating1'] + 
		($v['rating2'] * 2) + 
		($v['rating3'] * 3) +
		($v['rating4'] * 4) +
		($v['rating5'] * 5) +
		($v['rating6'] * 6) +
		($v['rating7'] * 7) +
		($v['rating8'] * 8) +
		($v['rating9'] * 9) +
		($v['rating10'] * 10);
	$n = $v['ratings'];
	if(!empty($n)){
		$rating = ($s / $n) ;
	}else{
		$rating = '0';
	}
	$rating = round($rating,1);
	return $rating;
}

function getStarImg($v){
	$v = $v / 2;
	$v = number_format($v, 1, '.', ',');
	switch ($v){
		case $v > 4.5:
			$p = 5;
			break;
		case $v > 4:
			$p = 45;
			break;
		case $v > 3.5:
			$p = 40;
			break;
		case $v > 3:
			$p = 35;
			break;
		case $v > 2.5:
			$p = 30;
			break;
		case $v > 2:
			$p = 25;
			break;
		case $v > 1.5:
			$p = 20;
			break;
		case $v > 1:
			$p = 15;
			break;
		case $v > 0.5:
			$p = 10;
			break;
		default:
			$p = 10;
	}
	return $p;
}

/* 原来的函数
function assignUser() {
	if(!empty($_SESSION['uid'])){
		$user['logintip'] = $_SESSION['username'].'，您好！&nbsp;<a href="/accounts/">会员中心</a> | <a href="/accounts/logout/">退出</a>';	
	}else{
		$user['logintip'] = '您好！请先&nbsp;<a href="/reg" >注册</a> 或 <a href="/login" >登录</a>';	
	}
	return $user;
} */
function assignUser() {  //为新浪微博设计的函数
	if(!empty($_SESSION['uid'])){
		$user['logintip'] = $_SESSION['username'].'，您好！&nbsp;<a href="/people/'.$_SESSION['uid'].'">我的电影</a> | <a href="/accounts/logout/">退出</a>';	
	}else{
		$user['logintip'] = '<a href="'. $_SESSION['apiurl'] . '"><img name="用新浪微博帐号登录" src="http://www.sinaimg.cn/blog/developer/wiki/32.png"  alt="用新浪微博帐号登录" /></a>';	
	}
	return $user;
}






function getReferer() {
	$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : getenv('HTTP_REFERER') ;
	if(empty($referer) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) {
		$referer = '';
	}
	return $referer;
}

function getUrl(){
	global $urlRouter;
	return $urlRouter;
}

function highlightWords($str, $keywords, $color = "#C60A00") {
    if (empty($keywords)) {
        return $str;
    }
    $keywords = split("[ \t\r\n,]+", $keywords);
    foreach($keywords as $val) {
        $tvar = eregi($val, $str, $regs);
        $finalrep    = '<font style="color:'.$color.';font-weight:bold">' . $regs[0] . '</font>';
    }
    $str = str_ireplace($regs[0], $finalrep, $str);
    return $str;
}

function htmlClear($htm){
	$search = array ("'<script[^>]*?>.*?</script>'si","'<[\/\!]*?[^<>]*?>'si","'([\r\n])[\s]+'","'&(quot|#34);'i","'&(amp|#38);'i","'&(lt|#60);'i","'&(gt|#62);'i","'&(nbsp|#160);'i","'&(iexcl|#161);'i","'&(cent|#162);'i","'&(pound|#163);'i","'&(copy|#169);'i","'&#(\d+);'e");
	$replace = array ("", "", "\\1", "\"", "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), "chr(\\1)");
	$text = preg_replace ($search, $replace, $htm);
	return $text;
}

function html2text($content){
	$content = preg_replace("/<style .*?<\/style>/is", "", $content);
	$content = preg_replace("/<script .*?<\/script>/is", "", $content);
	$content = preg_replace("/<br\s*\/?>/i", "\n", $content);
	$content = preg_replace("/<\/?p>/i", "\n", $content);
	$content = preg_replace("/<\/?td>/i", "\n", $content);
	$content = preg_replace("/<\/?div>/i", "\n", $content);
	$content = preg_replace("/<\/?blockquote>/i", "\n", $content);
	$content = preg_replace("/<\/?li>/i", "\n", $content);
	$content = strip_tags($content);
	$content = preg_replace("/\&\#.*?\;/i", "", $content);
	return $content;
}

function html2Txt($txt){
	$txt = html2text($txt);
	$txt = str_replace(' ','',$txt);
	$txt = str_replace("　","",$txt);
	return $txt;
}

function location($url){
	header("Location:".$url);
}

function htmlFilter($html){
	$allowedTags = array('<a>','<font>','<span>','<p>','<br>','<strong>','<hr>','<img>', '<b>','<em>','<u>');
	$value = strip_tags($html, implode('', $allowedTags));
    return $value;
}

function isPost(){
	if( count( $_POST ) > 0 ){
		return true;
	}else{
		return false;
	}
}

function makeDir($dir, $mode = "0777" ) {
	if( ! $dir ) return 0;
	$dir = str_replace( "\\", "/", $dir );
	$mdir = "";
	foreach( explode( "/", $dir ) as $val ){
	  $mdir .= $val."/";
	  if( $val == ".." || $val == "." || trim( $val ) == "" ) continue;
		  if( ! file_exists( $mdir ) ) {
				if(!@mkdir( $mdir, $mode )){
					return false;
				}
				@chmod($mdir,0777);
		  }
	}
	return is_dir($dir);
}

function makePage($pageParam){
	$pageCounts = ceil( $pageParam['pageTotal'] / $pageParam['rows'] );
	//TODO
	if($pageParam['page'] > $pageCounts){
		//pageError();
		//exit();
	}
	$prePage	= $pageParam['page'] - 1;
	$nextPage	= $pageParam['page'] + 1;
	$firstPage	= 1;
	$lastPage	= $pageCounts;
	$currentPage= $pageParam['page'];
	$totalPage	= $pageCounts;
	$url          = $pageParam['pageUrl'];
	$halfPer   = 4;
	$total = $totalPage + 1;
	$pageStr .= ($currentPage > 5)? "<a href=\"$url".$prePage."\"> &lt; </a><a href=\"$url".$firstPage."\">".$firstPage."</a><span >...</span>": "";
	for ( $i = $currentPage - $halfPer,$i > 1 || $i = 1 , $j = $currentPage + $halfPer, $j < $totalPage || $j = $totalPage;$i <= $j ;$i++ )	{
		$pageStr .= $i == $currentPage ? "<SPAN class=current>" . $i . "</SPAN>": "<a href=\"$url$i\">" . $i  . "</a>";
	}
	$pageStr .= ($currentPage < $totalPage - 4)? "...<a href=\"$url".$lastPage."\">".$lastPage."</a><a href=\"$url".$nextPage . "\"> &gt; </a>": "";
	$pageStr='<DIV class="pages">'.$pageStr.'</div>';
	return $pageStr;
}

function makeThumbImage($sourFile,$targetFile, $width='500', $height='500') {
	$data = getimagesize($sourFile);
	$imageInfo["width"] = $data[0];
	$imageInfo["height"]= $data[1];
	$imageInfo["type"] = $data[2];
	$imageInfo["name"] = basename($sourFile);
	$imageInfo["size"] = filesize($sourFile);
	$newName = substr($sourFile, 0, strrpos($sourFile, ".")) . "_thumb.jpg";
	//打开图片
	switch ($imageInfo["type"]){
		case 1:	$img = imagecreatefromgif($sourFile); break;
		case 2: $img = imagecreatefromjpeg($sourFile); break;
		case 3: $img = imagecreatefrompng($sourFile); break;
		default: return 0; break;
	}
	if (!$img){
		return "Create image failed";
	}
	//图片缩小
	$width = ($width > $imageInfo["width"]) ? $imageInfo["width"] : $width;
	$height = ($height > $imageInfo["height"]) ? $imageInfo["height"] : $height;
	$srcW = $imageInfo["width"];
	$srcH = $imageInfo["height"];

	//$height = min(round($srcH * $width / $srcW),$height);
	//$width = min(round($srcW * $height / $srcH),$width);

	if (function_exists("imagecreatetruecolor")) { //GD2.0.1
		$new = imagecreatetruecolor($width, $height);
		ImageCopyResampled($new, $img, 0, 0, 0, 0, $width, $height, $imageInfo["width"], $imageInfo["height"]);
	}else{
		$new = imagecreate($width, $height);
		ImageCopyResized($new, $img, 0, 0, 0, 0, $width, $height, $imageInfo["width"], $imageInfo["height"]);
	}
	$dir = dirname($targetFile);
	if(!is_dir($dir)){
		makeDir($dir);
	}
	//生成图片
	ImageJPEG($new, $targetFile, 100);
}

function thumbs($sourFile, $targetFile, $width, $height) {
	$data = getimagesize($sourFile);	
	$imageInfo["width"] = $data[0];
	$imageInfo["height"] = $data[1];
	$imageInfo["type"] = $data[2];
	$imageInfo["name"] = basename($sourFile);
	$imageInfo["size"] = filesize($sourFile);
	switch ($imageInfo["type"]){
		case 1:	$ThisPhoto = imagecreatefromgif($sourFile); break;
		case 2: $ThisPhoto = imagecreatefromjpeg($sourFile); break;
		case 3: $ThisPhoto = imagecreatefrompng($sourFile); break;
		default: return 0; break;
	}
	$scalc = max($imageInfo["width"] / $width, $imageInfo["height"] / $height);
	$nw = intval($imageInfo["width"] / $scalc);
	$nh = intval($imageInfo["height"] / $scalc);
	if ($width - $nw == 1) {
		$nw = $width;
	} 
	if ($height - $nh == 1) {
		$nh = $height;
	} 
	// 补宽
	if ($width - $nw > 0) {
		$nh = $nh + (($nh / $nw) * ($width - $nw));
		$nw = $width;
	} 
	// 补高
	if ($height - $nh > 0) {
		$nw = $nw + (($nw / $nh) * ($height - $nh));
		$nh = $height;
	}
	$nw = intval($nw);
	$nh = intval($nh);
	$px = ($width - $nw) / 2;
	$py = ($height - $nh) / 2;

	if (function_exists("imagecreatetruecolor")) {
		$NewPhoto = imagecreatetruecolor($width, $height);
		ImageCopyResampled($NewPhoto, $ThisPhoto,$px, $py,0, 0,$nw, $nh, $imageInfo["width"], $imageInfo["height"]);
	}else{
		$NewPhoto = imagecreate($width, $height);
		ImageCopyResized($NewPhoto, $ThisPhoto,$px, $py, 0, 0,$nw, $nh, $imageInfo["width"], $imageInfo["height"]);
	}
	$dir = dirname($targetFile);
	if(!is_dir($dir)){
		makeDir($dir);
	}
	ImageJPEG($NewPhoto, $targetFile, 100);
} 

function message($msg='',$direct = "0",$min = '3') {
	switch($direct){
		case '0'://提示
		$script = "";
		case '1'://提示刷新返回
		$script = 'location.href="'.$_SERVER["HTTP_REFERER"].'";';
		break;
		case '2'://提示返回
		$script = "history.back();";
		break;
		default://提示转向指定页面
		$script = 'location.href="'.$direct.'";';
	}
	if(empty($msg)){
		echo "<script language='javascript'>".$script."</script>";
	}else{
		echo '<script type="text/javascript" src="/static/js/jquery.min.js"></script>';
		echo '<link rel="Stylesheet" type="text/css" href="/static/js/jmodal/jquery.jmodal.css" />';
		echo '<script type="text/javascript" src="/static/js/jmodal/jquery.jmodal.js"></script>';
		echo "<script language='javascript'>
		$().ready(function() {	
			$.fn.jmodal({
				title: 'Message',
				content: '<BR>".$msg."<BR><BR>',
				buttonText: { ok: 'no', cancel: 'No' },
				okEvent: function(obj, args) {					
					args.complete();
					".$script.";
				}
			});
			window.setTimeout('".$script."',1600);
		});
		</script>";
	}	
    exit();
}

function pageError($msg='',$url='',$title='HTTP 404 未找到'){
	require_once (CLASS_PATH.'tpl/page_error.php');
	exit();
}

function run(){
	$do = getUrl();
	//de($do);
	$controller = APP_PATH.'action/'.$do['module'].'/'.$do['action'].'.php';
	//de($controller);
	if(file_exists($controller)){
		require_once(CLASS_PATH."class/template.class.php" );
		require_once( $controller );
		$thisAction = $do['action'];
		$module = new $thisAction ($this);
		$module->defaultAction();
	}else{
		$page = APP_PATH.'action/'.$do['module'].'/main.php';
		//de($page);
		if(!file_exists($page)){
			pageError();
		}
		require_once(CLASS_PATH."class/template.class.php" );
		require_once($page);
		$module = new main ( $this );
	}
}

function saveArray($file, $a1, $a2=null){
	if($a2) { $a1 = array_merge($a1, $a2);}
	$a1 = "<?php\n!defined(\"DCS_ROOT\") && die(\"Forbidden!\");\nreturn ".var_export($a1, true)."\n?>";
	return fileWrite($file, $a1);
}

function showRating($rating){
	$i=1;
	while($i <= $rating){
		$val .= '<img class="rating" src="'.PUB.'img/st.gif" vspace="0" alt="'.$rating.'分"/>';
		$i++;
	}
	return $val;
}


function text2js($l1, $l2=1){
    $I1 = str_replace(array("\r", "\n"), array('', '\n'), addslashes($l1));
    return $l2 ? "document.write(\"$I1\");" : $I1;
}

function txt2Html($str){ 
	$str = htmlspecialchars($str); 
	$str = nl2br($str);
	return $str; 
}



function urlRouter(){
	$path = strip_tags($_SERVER['REQUEST_URI']);
	$strpos=strpos($path,'.html');
	//de($strpos);
	if($strpos){
	   $path=substr($path,0,$strpos);
	}
	if($path['0'] == '/'){
		$path = substr($path,1);
	}
	//de($path);
	if(!empty($path)){
		$path = explode('/',$path);
		$router['module'] = $path[0];
		$router['action'] = (!empty($path[1])) ? $path[1] : 'main';
		$pathNum = sizeof($path);
		if($pathNum >= 3){
			for($i = 2; $i < $pathNum; $i++){
				$params[$i-1] = (isset($path[$i])) ? $path[$i] : '';
			}
			$router['params'] = $params;
		}
		unset($pathNum);
	}else{
		$router['module']='index';
		$router['action']='main';
		$router['params']=array();
	}
	return $router;
}

function writeCache($cachename,$obj,$cachedata = '',$appdir = '') {
	$cachedir = APP_PATH.'data/'.$appdir.'/';
	$cachefile = $cachedir.$cachename.'.php';
	$cachedata = '$'."$obj = " . var_export($cachedata,true) . ";\n";
	$cachedata = "<?php\n// cache file, DO NOT modify me!\n" . "//Created on "  . date("M j, Y, G:i") ."\nif(!defined('DCS_ROOT')) {exit('Access Denied');}\n\n$cachedata\n?>";
	fileWrite($cachefile,$cachedata);
}

function getNewsComment($update = false){
	$cache = DATA_PATH."cache/newscomment.php";
	if(is_file($cache)){
		$newcomment = require_once($cache);
	}
	if(empty($newcomment) || $update == true){
		$db = getDB();

		$newcomment = $db->getAll('news_comment','*',"",'addtime','0,10');		  
		foreach($newcomment as $k => $v ){
			$aids .= "'".$v['aid']."',";
		}
		$aids = substr($aids,0,-1);
		$articles = $db->getAll('news','id,url,title'," id IN($aids) ",'addtime');		
		foreach($articles as $k => $v ){
			$commentnews[$v['id']] =  $v;
		}
		foreach($newcomment as $k => $v) {
			$aid = $v['aid'];
			$newcomment[$k]['addtime'] = dateFormat($v['addtime']);
			$newcomment[$k]['author'] = empty($v['author']) ? '网友' : '<a href="/user/'.$v['uid'].'">'.$v['author'].'</a>';
			$newcomment[$k]['title'] = $commentnews[$aid]['title'];
			$newcomment[$k]['url'] = $commentnews[$aid]['url'];
		}
		saveArray(DATA_PATH.'cache/newscomment.php',$newcomment);
	}
	return $newcomment;
}


function getAds($var){
	$cache = DATA_PATH."cache/ads.php";
	if(is_file($cache)){
		$ads = require_once($cache);
	}
	$ad = $ads[$var];
	if(empty($ad) OR $ad['is_verify'] != '1'){
		return;
	}
	if($ad['type'] == '1'){
		echo '<img src="/static/upload/ads/'.$ad['files'].'" width="'.$ad['width'].'" height="'.$ad['height'].'"  />';		
	}elseif($ad['type'] == '3'){
		echo '<object type="application/x-shockwave-flash" data="/static/upload/ads/'.$ad['files'].'"  width="'.$ad['width'].'" height="'.$ad['height'].'" > 
		<param name="movie" value="/static/upload/ads/'.$ad['files'].'"/>
		<embed src="/static/upload/ads/'.$ad['files'].'"  width="'.$ad['width'].'" height="'.$ad['height'].'" ></embed> 
		</object>';
	}elseif($ad['type'] == '2'){
		echo $ad['content'];
	}
}

function updateAds(){	
	$DB = getDB();		
	$DB->query("SELECT * FROM ads ORDER BY id DESC ");
	$ads = $DB->fetchAll();
	saveArray(DATA_PATH.'cache/ads.php',$ads);	
}


//**********************新增，字符截断处理函数××××××××××××××××××××××××××××××××××

function cut_str($sourcestr,$cutlength) 
{ 
   $returnstr=''; 
   $i=0; 
   $n=0; 
   $str_length=strlen($sourcestr);//字符串的字节数 
   while (($n<$cutlength) and ($i<=$str_length)) 
     { 
      $temp_str=substr($sourcestr,$i,1); 
      $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码 
      if ($ascnum>=224)    //如果ASCII位高与224，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符         
         $i=$i+3;            //实际Byte计为3
         $n++;            //字串长度计1
      }
        elseif ($ascnum>=192) //如果ASCII位高与192，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符 
         $i=$i+2;            //实际Byte计为2
         $n++;            //字串长度计1
      }
        elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,1); 
         $i=$i+1;            //实际的Byte数仍计1个
         $n++;            //但考虑整体美观，大写字母计成一个高位字符
      }
        else                //其他情况下，包括小写字母和半角标点符号，
      { 
         $returnstr=$returnstr.substr($sourcestr,$i,1); 
         $i=$i+1;            //实际的Byte数计1个
         $n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
      } 
     } 
           if ($str_length>$cutlength){
          $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
      }
      return $returnstr; 

}

